<?php

namespace app\backend\controller;

use app\backend\model\User;
use think\Controller;
use think\Request;
use think\captcha\Captcha;

class Login extends Controller
{
    /**
     * @return mixed
     * @return \think\Response
     *
     */
    public function index()
    {

        return $this->fetch('/login', [
            'pass' => md5("123456Euav0J"),
        ]);

    }

    /**
     * 用户登录
     *
     * @param  \think\Request  $request
     * @return \think\Response
     *
     */
    public function login(Request $request)
    {
        //校验验证码
        $value = $request->post('verify');
        $captcha = new Captcha();
        if( !$captcha->check($value))
        {
            return json([
                'status' => '0',
                'message' => '验证码错误',
            ]);
            exit;
        }

        //获取登录用户信息并进行校验
        $username = $request->post('username');
        $password = $request->post('password');

        $role = User::get([
            'username' => $username,
        ]);

        $password = strtolower($password).$role->salt;
        $password = md5($password);

        if ($password != $role->password)
        {
            return json([
                "status" => "0",
                "message" => "用户名或密码错误",
            ]);
            exit;
        }

        $status = 1;
        $msg = "登陆成功,欢迎". $username ."回来";
        session('username', $username);
        session('uid', $role->id);

        return json([
            'status' => $status,
            'message' => $msg,
        ]);
    }

    /**
     *
     * 用户退出登录
     */
    public function logout()
    {
        session('username', null);
        return $this->redirect('login');
    }
}
